package com.czk.config;

import com.czk.domain.Constants;
import com.czk.domain.FileBurstData;
import com.czk.domain.FileBurstInstruct;
import com.czk.domain.FileTransferProtocol;
import com.czk.utils.FileUtil;
import com.czk.utils.MsgUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/23 13:57
 */
public class MyClientChannelHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 数据格式验证
        if (!(msg instanceof FileTransferProtocol)) return;
        // 强转
        FileTransferProtocol fileTransferProtocol = (FileTransferProtocol) msg;
        // 拿到文件类型
        Integer transferType = fileTransferProtocol.getTransferType();
        // 0传输文件'请求'、1文件传输'指令'、2文件传输'数据'
        switch (transferType) {
            case 1:
                FileBurstInstruct fileBurstInstruct = (FileBurstInstruct) fileTransferProtocol.getTransferObj();
                if (Constants.FileStatus.COMPLETE == fileBurstInstruct.getStatus()) {
                    // 传输完成
                    ctx.flush();
                    ctx.close();
                    // 结束虚拟机
                    System.exit(-1);
                    return;
                }
                FileBurstData fileBurstData = FileUtil.readFile(fileBurstInstruct.getClientUrl(), fileBurstInstruct.getReadPosition());
                // 写回
                ctx.writeAndFlush(MsgUtil.buildTransferData(fileBurstData));
                System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 客户端传输文件信息。 FILE：" + fileBurstData.getFileName() + " SIZE(byte)：" + (fileBurstData.getEndPos() - fileBurstData.getBeginPos()));
                break;
            default:
                break;
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息：\r\n" + cause.getMessage());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("断开链接" + ctx.channel().localAddress().toString());
        super.channelInactive(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("链接报告开始");
        System.out.println("链接报告信息：本客户端链接到服务端。channelId：" + channel.id());
        System.out.println("链接报告IP:" + channel.localAddress());
        System.out.println("链接报告完毕");
    }
}
